<script setup>
import { useRouter, useRoute } from 'vue-router'
import { ref, onMounted, onUnmounted } from 'vue'
// import defCodeUrl from '@/assets/code.png'
import {
  useGetImgCodeService,
  useGetTextCodeService,
  uesLoginService
} from '@/api/requsets/index.js'
import { showFailToast, showSuccessToast } from 'vant'
import { useUserStore } from '@/stores/index.js'

//当前路由对象
const router = useRouter()

//
const route = useRoute()

// 用户信息仓库
const userStore = useUserStore()

// 表单实例
const form = ref()

// 登录 | 注册 表单 v-model响应实例
const formData = ref({
  mobile: '', // 手机号
  captchaCode: '', //图形验证码
  smsCode: '' // 短信验证码
})

// 验证码图片
const imgUrl = ref('')

// 验证码key
const captchaKey = ref()

// 获取图形验证码的回调
const getImgCode = async () => {
  const {
    data: { base64, key }
  } = await useGetImgCodeService()
  imgUrl.value = base64
  captchaKey.value = key
}
onMounted(async () => {
  await getImgCode()
})

// 总秒数
const totalSeconds = ref(10)
// 当前秒数
const nowSeconds = ref(10)
// 定时器id
const timer = ref()
// 是否发送短信
const isSend = ref(false)

// 获取短信验证码的回调
const getTextCodec = () => {
  form.value
    .validate(['mobile', 'imgCode'])
    .then(async () => {
      isSend.value = true
      timer.value = setInterval(async () => {
        nowSeconds.value--
        if (nowSeconds.value === 0) {
          clearInterval(timer.value)
          timer.value = null
          nowSeconds.value = totalSeconds.value
          isSend.value = false
        }
      }, 1000)
      const { data } = await useGetTextCodeService({
        form: {
          mobile: formData.value.mobile,
          captchaCode: formData.value.captchaCode,
          captchaKey: captchaKey.value
        }
      })
      console.log(data)
    })
    .catch((err) => {
      showFailToast(err)
      console.log(err.message)
      return
    })
}
onUnmounted(() => {
  clearInterval(timer.value)
})

// 点击登录的回调
const toLogin = () => {
  form.value
    .validate(['mobile', 'imgCode', 'textCode'])
    .then(async () => {
      const { data } = await uesLoginService({
        form: {
          isParty: false,
          partyData: {},
          mobile: formData.value.mobile,
          smsCode: formData.value.smsCode
        }
      })

      userStore.setUser({ user_id: data.userId })
      userStore.setToken(data.token)
      // 判断有无回跳地址 若有回跳地址，则回跳页面
      const url = route.query.backUrl || '/'
      await router.replace(url)
      // await router.push('/home')
      showSuccessToast('登录成功')
    })
    .catch((err) => {
      showFailToast(err)
      console.error(err.message)
    })
}
</script>

<template>
  <div class="login">
    <van-nav-bar
      title="会员登录"
      class="title"
      left-arrow
      :submit-on-enter="false"
      @click-left="router.go(-1)"
    />
    <div class="header">
      <h3>手机号登录</h3>
      <p>未注册的手机号登录后将自动注册</p>
    </div>
    <van-form class="form" @submit="toLogin" ref="form">
      <van-cell-group inset>
        <div class="field">
          <van-field
            autocomplete="off"
            v-model.trim="formData.mobile"
            name="mobile"
            placeholder="请输入手机号"
            :rules="[
              { required: true, message: '请输入手机号' },
              {
                pattern: /^(1[3456789]\d{9})$/,
                message: '请输入正确的手机号码'
              }
            ]"
          />
        </div>
        <div class="field">
          <van-field
            autocomplete="off"
            v-model.trim="formData.captchaCode"
            name="imgCode"
            placeholder="请输入图形验证码"
            :rules="[{ required: true, message: '请输入图形验证码' }]"
          />
          <img v-if="imgUrl" :src="imgUrl" @click="getImgCode" />
        </div>
        <div class="field">
          <van-field
            autocomplete="off"
            v-model.t.trim="formData.smsCode"
            name="textCode"
            placeholder="请输入短信验证码"
            :rules="[{ required: true, message: '请输入短信验证码' }]"
          />
          <van-button v-if="!isSend" class="codeBtn" @click="getTextCodec"
            >发送验证码</van-button
          >
          <van-button disabled v-else class="codeBtn"
            >重新发送({{ nowSeconds }})秒</van-button
          >
        </div>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button class="btn" round block native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style scoped lang="less">
.login {
  .header {
    padding: 20px;
    margin: 20px auto;
    //text-align: center;
    h3 {
      font-weight: normal;
      font-size: 26px;
      margin-bottom: 10px;
    }
    p {
      color: #b8b8b8;
    }
  }

  .form {
    .field {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      box-sizing: border-box;
      border-bottom: 1px solid #f3f1f2;
      color: #000;
      .codeBtn {
        width: 40%;
        height: 40%;
        border: none;
        background: transparent;
        color: #cea26a;
        font-size: 14px;
      }
      img {
        width: 30%;
        height: 30%;
      }
    }
  }

  .btn {
    border: none;
    color: #fff;
    background: linear-gradient(90deg, #ecb53c, #ff9211);
  }
}
</style>
